package com.hmall.order.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmall.domain.constant.MqConstant;
import com.hmall.domain.pojo.Order;
import com.hmall.domain.pojo.OrderDetail;
import com.hmall.feign.common.ItemFeignClient;
import com.hmall.order.service.IOrderService;
import com.hmall.order.service.OrderDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 订单支付监听类
 *
 * @Author XiaoJiangShi
 * @Date 2022/8/14 11:56
 * @Blog blog.XiaoJiangShi.net/996.mba
 * @Description: 订单支付监听类
 */
@Slf4j
@Component
public class OrderPayListener {

    @Autowired
    private ItemFeignClient itemFeignClient;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private OrderDetailService detailService;

    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = MqConstant.ORDER_COMMIT_QUEUE, durable = "true"),
                    exchange = @Exchange(MqConstant.ORDER_DL_EXCHANGE),
                    key = MqConstant.ORDER_DL_ROUT
            ), @QueueBinding(value = @Queue(MqConstant.ORDER_COMMIT_QUEUE),
            exchange = @Exchange(MqConstant.ORDER_DL_EXCHANGE),
            key = MqConstant.ORDER_COMMIT_ROUT)})
    public void orderPayAndItemListener(String message) {
        log.info("从死信接收的消息为message：[{}]", message);
        Order order = orderService.getById(Long.parseLong(message));
        Integer status = order.getStatus();
        if (status == 1) {
            LambdaQueryWrapper<OrderDetail> qu = new LambdaQueryWrapper<>();
            qu.eq(OrderDetail::getOrderId, Long.parseLong(message));
            OrderDetail detail = detailService.getOne(qu);
            Long itemId = detail.getItemId();
            Integer num = detail.getNum();
            order.setStatus(5);
            orderService.updateById(order);
            itemFeignClient.reduceIvo(itemId, num, status);
        }
    }
}

